local FileSystem = Tubes.FileSystem
FileSystem._Base = {}
local Base = FileSystem._Base
Base.__index = Base

local PermissionList = {
	["Create Folder"] = true,
	["Delete"] = true,
	["Edit Permissions"] = true,
	["Read"] = true,
	["Rename"] = true,
	["View Folder"] = true,
	["Write"] = true
}

--[[
	Events
	
	ItemAdded (Base parent, Base child)
	ItemRemoved (Base parent, Base child)
]]

function Base:ctor (name)
	self.Name = name or ""
	self.NiceName = name or ""
	
	self.Parent = nil
	self.FileCount = 0
	self.FolderCount = 0
	
	self.Type = "Unknown"
	self.Data = nil
	
	self.EventProvider = Tubes.EventProvider (self, function ()
		return self.Parent and self.Parent.EventProvider or nil
	end)
	
	-- Permissions
	self.Permissions = Tubes.PermissionBlock (function ()
		return self.Parent and self.Parent.Permissions or nil
	end)
	self.Permissions:SetName (name)
	self.Permissions:SetPermissionList (PermissionList)
end

function Base:Delete (ply, name)
	if not self:PlayerHasPermission (ply, "Delete") then
		return
	end
	if self.Parent then
		if self:IsFolder () then
			self.Parent.FolderCount = self.Parent.FolderCount - 1
		else
			self.Parent.FileCount = self.Parent.FileCount - 1
		end
		self.Parent.Children [self.Name] = nil
	end
	self:DispatchEvent ("ItemDeleted", self.Parent, self)
end

function Base:GetFullPath ()
	local Path = ""
	local Parent = self
	while Parent:GetParent () do	-- Ignore the root folder.
		Path = Parent:GetName () .. "/" .. Path
		Parent = Parent:GetParent ()
	end
	return Path:sub (1, -2)
end

function Base:GetOwner ()
	return self.Permissions:GetOwner ()
end

function Base:GetOwnerName ()
	return self.Permissions:GetOwnerName ()
end

function Base:GetName ()
	return self.Name
end

function Base:GetNiceName ()
	return self.NiceName or self.Name or ""
end

function Base:GetParent ()
	return self.Parent
end

function Base:GetPermissions ()
	return self.Permissions
end

function Base:HasNiceName ()
	return self.NiceName and self.NiceName ~= "" and self.NiceName ~= self.Name
end

function Base:IsFolder ()
	return false
end

function Base:IsOwnerServer ()
	return not self:GetOwner () and self:GetOwnerName () == "Server"
end

function Base:IsReal ()
	return false
end

function Base:ItemExists ()
	return false
end

function Base:PlayerHasPermission (ply, permission)
	return self.Permissions:GetPlayerPermission (ply, permission)
end

function Base:Refresh ()
end

function Base:SetOwner (owner, ownerName, ownerSteamID)
	self.Permissions:SetOwner (owner, ownerName, ownerSteamID)
end

function Base:SetNiceName (name)
	local LastNiceName = self:GetNiceName ()
	self.NiceName = name
	self.Permissions:SetName (name or self.Name)
	
	self:DispatchEvent ("ItemRenamed", self, self:GetName (), LastNiceName)
end

function Base:SetParent (parent)
	self.Parent = parent
end